import os
import sys
import psutil
import datetime
import warnings
from multiprocessing import Pool

import pandas as pd

sys.path.append('..')
warnings.filterwarnings('ignore')

from tools.setting import DATA_DIR
from API.deribit import get_active_instruments, get_instruments, get_last_trades_by_instrument
from tools.logger import logger
OPTION_DATA_DIR = os.path.join(DATA_DIR, 'deribit_option_data')
os.makedirs(OPTION_DATA_DIR, exist_ok=True)


def reload_one_option_trade_data(instrument_name):
    # 获取单个期权合约的交易数据
    file_name = os.path.join(OPTION_DATA_DIR, f'{instrument_name}.csv')
    df = get_last_trades_by_instrument(instrument_name=instrument_name, count=10000)
    if df is not None:
        df.to_csv(file_name)

def reload_all_option_trade_data():
    # 获取全部期权合约的交易数据
    all_instrument_info = get_instruments(currency='BTC', kind='option')
    instrument_list = all_instrument_info['instrument_name']
    p = Pool(min(int(psutil.cpu_count(logical=True) * 0.8), 60))
    p.map(reload_one_option_trade_data, instrument_list)
    p.close()
    p.join()

def update_deribit_option_trade_data(days_delta=5):
    # 更新活跃合约的交易数据，已过期合约不需要更新
    logger.info('获取所有期权合约信息')
    active_instruments_file = os.path.join(DATA_DIR, 'deribit_option_information\\active_instruments.csv')
    all_instruments_file = os.path.join(DATA_DIR, 'deribit_option_information\\all_instruments.csv')
    if os.path.exists(active_instruments_file):
        active_instruments_last_update = pd.read_csv(active_instruments_file)
        active_instruments_last_update = list(active_instruments_last_update['instrument_name'])
    else:
        active_instruments_last_update = []
    date_flag = (datetime.datetime.now() - datetime.timedelta(days=days_delta)).strftime('%Y-%m-%d %H:%M:%S')
    all_instrument_info = get_instruments(currency='BTC', kind='option')
    all_instrument_info.to_csv(all_instruments_file, index=False)
    filtered_instrument = all_instrument_info[all_instrument_info['expiration_datetime'] >= date_flag]
    filtered_instrument = list(filtered_instrument['instrument_name'])
    instruments_to_update = list(set(active_instruments_last_update) | set(filtered_instrument))
    logger.info('获取所有期权合约交易信息')
    p = Pool(min(int(psutil.cpu_count(logical=True) * 0.8), 60))
    p.map(reload_one_option_trade_data, instruments_to_update)
    p.close()
    p.join()
    logger.info('保存当期活跃期权合约信息')
    active_instruments = get_active_instruments()
    active_instruments.to_csv(active_instruments_file, index=False)

if __name__ == '__main__':
    update_deribit_option_trade_data()
